package com.muc.plugin.handler;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.dom4j.Element;
import org.jivesoftware.openfire.IQHandlerInfo;
import org.jivesoftware.openfire.XMPPServer;
import org.jivesoftware.openfire.auth.UnauthorizedException;
import org.jivesoftware.openfire.handler.IQHandler;
import org.jivesoftware.openfire.muc.spi.LocalMUCRoom;
import org.jivesoftware.openfire.muc.spi.MultiUserChatServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xmpp.packet.IQ;

import com.muc.plugin.dao.MUCDao;

/**
 * 用户参与的房间 查询 (应该要改为主动的)
 *
 */
public class MUCUserJoinedRoomsQueryIQHandler extends IQHandler {

    private IQHandlerInfo info;

    private static final String NAME_SPACE = "xls:muc-user-joined-rooms";

    private static final String MODULE_NAME = "jid join rooms query";

    private static final Logger log = LoggerFactory.getLogger(MUCUserJoinedRoomsQueryIQHandler.class);

    public MUCUserJoinedRoomsQueryIQHandler() {
        super(MODULE_NAME);
        info = new IQHandlerInfo("query", NAME_SPACE);
    }

    @Override
    public IQHandlerInfo getInfo() {
        return info;
    }

    @Override
    public IQ handleIQ(IQ packet) throws UnauthorizedException {
        log.info("execute " + this.getClass().getName() + " method: handleIQ");
        IQ reply = IQ.createResultIQ(packet);
        reply.setChildElement("muc", NAME_SPACE);

        List<Map<String, String>> data = MUCDao.getMUCInfo(packet.getFrom().toBareJID());
        if (data == null || data.isEmpty()) {
            data = new ArrayList<Map<String, String>>();
        }

        XMPPServer server = XMPPServer.getInstance();
        Map<String, String> map = null;
        MultiUserChatServiceImpl mucService = null;
        for (int i = 0, len = data.size(); i < len; i++) {
            map = data.get(i);
            String serviceID = map.get("serviceID");
            mucService = (MultiUserChatServiceImpl) server.getMultiUserChatManager().getMultiUserChatService(Long.parseLong(serviceID));
            String roomName = map.get("name");
            LocalMUCRoom room = (LocalMUCRoom) mucService.getChatRoom(roomName);
            // 增加room和account的信息
            Element roomElement = reply.getChildElement().addElement("room");
            roomElement.setText(room.getJID().toBareJID());
            roomElement.addAttribute("account", packet.getFrom().toFullJID())
                    .addAttribute("roomid", room.getID() + "")
                    .addAttribute("description", room.getDescription())
                    .addAttribute("naturalname", room.getNaturalLanguageName());
        }
        reply.setType(IQ.Type.result);
        return reply;
    }

}
